import React from 'react';
import { Form, Breadcrumb, Row, Col, Input, DatePicker, Select, Modal, Button, Pagination, Icon, Cascader, Table, message } from 'antd';
import { Link } from 'react-router';
import $ from 'jquery';
import Config from '../../../common/config';
import './crmOrderlist.less';
import region from '../../../common/region';
import moment from 'moment';

const FormItem = Form.Item;
const Option = Select.Option;
const config = new Config();
const InputGroup = Input.Group;
const { RangePicker } = DatePicker;
const token = sessionStorage.getItem('token');

class CrmOrderlist extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            keyword: sessionStorage.getItem('keyword') ? sessionStorage.getItem('keyword').split(',') : [], // 关键词
            userInfo: JSON.parse(sessionStorage.getItem('UserInfo')), // 用户信息
            orderPage: 1, // 订单的当前页
            orderPageSize: 10, // 订单的每页显示的条数
            orderTotal: 0, // 订单的总数
            orderList: [], // 订单列表
            orderSizeOptions: ['10', '20', '30', '40'], // 订单的条数选择
            orderStatus: undefined, // 订单状态
            dateType: undefined, // 时间类型
            startDate: null, // 开始时间
            endDate: null, // 结束时间
            depositStatus: undefined, // 定金状态
            assigningVisible: false, // 分配模态框
            staffStatus: undefined, // 员工状态
            staffPage: 1, // 员工的当前页
            staffPageSize: 10, // 员工的每页显示的条数
            staffTotal: 0, // 员工的总数
            modalStaffList: [], // 模态框中员工列表
            staffSizeOptions: ['10', '20', '30', '40'], // 员工的条数选择
            customerSource: [], // 客户渠道
            currentCustomerSource: undefined, // 当前选中的客户渠道
            productVisibile: false, // 商品的模态框
            updateOrderProduct: {}, // 修改订单的商品详情
            productStatus: false, // 商品的状态
            productDelVisible: false, // 商品删除确认模态框
            deleteProduct: {}, // 将要删除的商品
            addProductVisible: false, // 添加商品模态框
            productList: [], // 商品列表
            productName: '', // 商品名称
            productPage: 1, // 商品的当前页
            productPageSize: 10, // 商品的每页显示的条数
            productTotal: 0, // 商品的总数
            categoryList: [], // 分类列表
            currentCategoryId: '', // 当前分类ID
            departmentList: [], // 部门列表
            staffList: [], // 员工列表
            currentStaff: undefined, // 当前选中的人员
            currentDepartment: undefined, // 当前选中的部门
            currentDepartmentList: [], // 当前选中的部门列表
            selectOrder: [], // 选中的订单
            assigning: false, //分配客户弹出框
            modalDepartment: '', // 模态框中的部门选择
            modalDepartmentList: [], // 模态框中的部门值
            publicVisible: false, // 公共模态框
            publicStatus: '', // 公共模态框的状态 1:订单审核 2:恢复订单状态 3:定金审核 4:恢复定金状态 5:签收 6:恢复仓库状态 7:导出
            payType: [], // 支付类型
            currentPayType: [], // 当前支付类型值
            orderMoneySum: 0.00, // 总金额
            collectionMoneySum: 0.00, // 代收金额
            depositSum: 0.00 // 定金
        }
    }

    componentDidMount() {
        const state = this.props.location.state;
        if (state) {
            const { page: orderPage, pageSize: orderPageSize, orderStatus, dateType, startDate, endDate, depositStatus, customerSourceId: currentCustomerSource, currentDepartment, currentDepartmentList, currentStaff, productName, consigneeName, shipOrderNumber, consigneePhone, parcelNumber, currentPayType, staffList } = state;
            this.props.form.setFieldsValue({
                productName,
                consigneeName,
                shipOrderNumber,
                consigneePhone,
                parcelNumber
            });
            this.setState({
                orderPage,
                orderPageSize,
                orderStatus,
                dateType,
                startDate: startDate ? moment(startDate, 'YYYY-MM-DD') : undefined,
                endDate: endDate ? moment(endDate, 'YYYY-MM-DD') : undefined,
                depositStatus,
                currentCustomerSource,
                currentDepartment,
                currentDepartmentList,
                currentStaff,
                staffList,
                currentPayType
            }, () => {
                this.getOrderList();
            });
        } else {
            this.getOrderList();
        }
        this.getCustomerSource();
        this.getDepartment();
        this.getPayType();
    }

    // 获取订单列表
    getOrderList() {
        const { productName, consigneeName, shipOrderNumber, consigneePhone, parcelNumber } = this.props.form.getFieldsValue();
        const { userInfo, orderPage: page, orderPageSize: pageSize, orderStatus, dateType, startDate, endDate, depositStatus, currentCustomerSource: customerSourceId, currentDepartment, currentStaff, currentPayType } = this.state;
        $.ajax({
            url: `${config.CrmOrder}/orderList`,
            type: 'get',
            headers: {
                'Authorization': 'Bearer ' + token,
            },
            data: {
                id: userInfo.id,
                page,
                pageSize,
                productName,
                consigneeName,
                shipOrderNumber,
                consigneePhone,
                parcelNumber,
                orderStatus,
                dateType,
                startDate: startDate ? startDate.format('YYYY-MM-DD') : undefined,
                endDate: endDate ? endDate.format('YYYY-MM-DD') : undefined,
                depositStatus,
                customerSourceId,
                departmentId: currentDepartment,
                staffId: currentStaff,
                payTypeId: currentPayType[currentPayType.length - 1]
            },
            success: res => {
                console.log('获取订单列表', res);
                if (res.code === 200) {
                    let orderMoneySum = 0;
                    let collectionMoneySum = 0;
                    let depositSum = 0;
                    res.rows.forEach(item => {
                        item.key = item.orderId;
                        orderMoneySum += Number(item.orderMoney);
                        collectionMoneySum += Number(item.collectionMoney);
                        depositSum += Number(item.depositOne) + (Number(item.depositTwo) || 0);
                    });
                    this.setState({
                        orderTotal: res.count,
                        orderList: res.rows,
                        orderMoneySum: orderMoneySum.toFixed(2),
                        collectionMoneySum: collectionMoneySum.toFixed(2),
                        depositSum: depositSum.toFixed(2)
                    });
                }
            }
        });
    }

    // 显示订单表头
    showOrderColumns() {
        return [{
            title: '订单编号',
            dataIndex: '',
            width: '6%',
            render: record => {
                return <a href='javascript:void(0)' onClick={this.showProduct.bind(this, record.orderId)}>{record.orderId}</a>
            }
        }, {
            title: '下单时间',
            dataIndex: 'createDate',
            width: '6%',
        }, {
            title: '归属人',
            dataIndex: 'managerName',
            width: '6%',
        }, {
            title: '客户姓名',
            dataIndex: 'consigneeName',
            width: '6%',
        }, {
            title: '联系方式',
            dataIndex: 'consigneePhone',
            width: '6%',
        }, {
            title: '订单状态',
            dataIndex: '',
            width: '6%',
            render(record) {
                let text;
                switch (record.orderStatus) {
                    case 0:
                        text = '未处理';
                        break;
                    case 1:
                        text = '已处理';
                        break;
                    case 2:
                        text = '待发货';
                        break;
                    case 3:
                        text = '已发货';
                        break;
                    case 4:
                        text = '已签收';
                        break;
                }
                return text;
            }
        }, {
            title: '订单金额',
            dataIndex: 'orderMoney',
            width: '6%',
        }, {
            title: '代收金额',
            dataIndex: 'collectionMoney',
            width: '6%',
        }, {
            title: '定金/支付方式',
            dataIndex: '',
            width: '8%',
            render(record) {
                let text1 = <p>{record.depositOne}/{record.onePayTypeName}</p>
                let text2;
                if (record.twoPayTypeId) {
                    text2 = <p>{record.depositTwo}/{record.twoPayTypeName}</p>
                }
                return <div>{text1}{text2}</div>;
            }
        }, {
            title: '定金状态',
            dataIndex: '',
            width: '6%',
            render(record) {
                let text;
                switch (record.depositStatus) {
                    case 0:
                        text = '未收款';
                        break;
                    case 1:
                        text = '已收款';
                        break;
                    case 2:
                        text = '待定';
                        break;
                }
                return text;
            }
        }, {
            title: '详细地址',
            dataIndex: '',
            width: '8%',
            render(record) {
                return record.consigneeArea.split(' ').join('') + record.consigneeDetail;
            }
        }, {
            title: '审核时间',
            dataIndex: 'examineDate',
            width: '6%',
        }, {
            title: '签收时间',
            dataIndex: 'signDate',
            width: '6%',
        }, {
            title: '订单审核人',
            dataIndex: 'examinerName',
            width: '6%',
        }, {
            title: '详情',
            dataIndex: '',
            width: '6%',
            render: record => {
                const { productName, consigneeName, shipOrderNumber, consigneePhone, parcelNumber } = this.props.form.getFieldsValue();
                const { orderPage: page, orderPageSize: pageSize, orderStatus, dateType, startDate, endDate, depositStatus, currentCustomerSource: customerSourceId, currentDepartment, currentDepartmentList, currentStaff, currentPayType, staffList } = this.state;
                const paths = {
                    pathname: `/crmorderdetail/${record.orderId}`,
                    state: {
                        page,
                        pageSize,
                        productName,
                        consigneeName,
                        shipOrderNumber,
                        consigneePhone,
                        parcelNumber,
                        orderStatus,
                        dateType,
                        startDate: startDate ? startDate.format('YYYY-MM-DD') : undefined,
                        endDate: endDate ? endDate.format('YYYY-MM-DD') : undefined,
                        depositStatus,
                        customerSourceId,
                        currentDepartment,
                        currentDepartmentList,
                        currentStaff,
                        currentPayType,
                        staffList,
                        returnUrl: 1
                    }
                };
                return <Link to={paths}>详情</Link>
            }
        }];
    }

    // 表头的选择框
    showRowSelection() {
        return {
            onSelect: (record, selected, selectedRows) => {
                this.setState({
                    selectOrder: selectedRows
                });
            },
            onSelectAll: (selected, selectedRows) => {
                this.setState({
                    selectOrder: selectedRows
                });
            }
        }
    }

    // 选择订单的分页
    changeOrderPage(page) {
        this.setState({
            orderPage: page
        }, () => {
            this.getOrderList();
        });
    }

    // 选择订单的每页显示的条数
    changeOrderSize(page, pageSize) {
        this.setState({
            orderPage: page,
            orderPageSize: pageSize
        }, () => {
            this.getOrderList();
        });
    }

    // 选择订单状态
    selectOrderStatus(value) {
        this.setState({
            orderStatus: value
        });
    }

    // 选择时间类型
    selectDateType(value) {
        this.setState({
            dateType: value
        });
    }

    // 选择起始时间
    selectStartDate(date) {
        this.setState({
            startDate: date
        });
    }

    // 选择结束时间
    selectEndDate(date) {
        this.setState({
            endDate: date
        });
    }

    // 选择定金状态
    selectDepositStatus(value) {
        this.setState({
            depositStatus: value
        });
    }

    // 搜索订单列表
    searchOrderList() {
        this.setState({
            orderPage: 1
        }, () => {
            this.getOrderList();
        });
    }

    // 重置订单列表搜索条件
    resetOrderList() {
        this.props.form.resetFields();
        this.setState({
            orderStatus: undefined,
            dateType: undefined,
            startDate: null,
            endDate: null,
            depositStatus: undefined,
            currentCustomerSource: undefined,
            currentStaff: undefined,
            currentDepartmentList: [],
            currentPayType: []
        }, () => {
            this.getOrderList();
        });
    }

    // 新建订单
    setOrder() {
        this.props.changeMenu('crmSetOrder');
        location.hash = '/crmSetOrder';
    }

    // 显示分配模态框
    showAssigningModal() {
        const { selectOrder } = this.state;
        if (!selectOrder.length) {
            return message.error('请先选择订单!');
        }
        this.setState({
            assigningVisible: true
        });
        this.getStaffList();
    }

    // 隐藏分配模态框
    hiddenAssigningModal() {
        this.setState({
            assigningVisible: false,
            staffStatus: undefined,
            modalDepartmentList: []
        });
        this.props.form.resetFields(['staffText']);
    }

    // 显示员工表头
    showStaffColumns() {
        return [{
            title: '姓名',
            dataIndex: 'username',
            width: '7%',
        }, {
            title: '登录名',
            dataIndex: 'userid',
            width: '6%',
        }, {
            title: '手机号',
            dataIndex: 'phone',
            width: '6%',
        }, {
            title: '部门',
            dataIndex: 'depname',
            width: '6%',
        }, {
            title: '状态',
            dataIndex: '',
            width: '4%',
            render(record) {
                let text;
                switch (record.status) {
                    case 0:
                        text = '离职';
                        break;
                    case 1:
                        text = '在职';
                        break;
                    case 2:
                        text = '试用期';
                        break;
                }
                return text;
            }
        }, {
            title: '性别',
            dataIndex: '',
            width: '6%',
            render(record) {
                let text;
                switch (record.gender) {
                    case 0:
                        text = '男';
                        break;
                    case 1:
                        text = '女';
                        break;
                    case 2:
                        text = '保密';
                        break;
                }
                return text;
            }
        }, {
            title: '角色',
            dataIndex: '',
            width: '4%',
            render: record => {
                return JSON.parse(record.roles).join(',')
            }
        }, {
            title: '选择',
            dataIndex: '',
            width: '5%',
            render: record => {
                return <div><a href='javascript:void(0)' onClick={this.allotOrder.bind(this, record)}>确认选择</a></div>;
            }
        }];
    }

    // 获取员工列表
    getStaffList() {
        const { staffStatus, staffPage, staffPageSize, modalDepartment, userInfo } = this.state;
        const staffText = this.props.form.getFieldValue('staffText');
        $.ajax({
            url: `${config.JuseManager}/manager/filter`,
            type: 'post',
            headers: {
                'Authorization': 'Bearer ' + token,
            },
            data: {
                id: userInfo.id,
                value: staffText,
                department: modalDepartment || userInfo.department,
                status: staffStatus,
                page: staffPage,
                pageSize: staffPageSize
            },
            success: res => {
                console.log('获取员工列表', res);
                if (res.code === 200) {
                    console.log(res.data.list);
                    res.data.list.forEach((item, index) => {
                        item.key = index;
                    })
                    this.setState({
                        modalStaffList: res.data.list,
                        staffTotal: res.data.total
                    });
                }
            }
        });
    }

    // 选择客户状态
    selectStaffStatus(value) {
        this.setState({
            staffStatus: value
        });
    }

    // 选择员工的分页
    changeStaffPage(page) {
        this.setState({
            staffPage: page
        }, () => {
            this.getStaffList();
        });
    }

    // 选择员工的每页显示的条数
    changeStaffSize(page, pageSize) {
        this.setState({
            staffPage: page,
            staffPageSize: pageSize
        }, () => {
            this.getStaffList();
        });
    }

    // 获取客户渠道
    getCustomerSource() {
        $.ajax({
            url: `${config.CrmSettings}/crm_customersource/BindSource`,
            type: 'post',
            headers: {
                'Authorization': 'Bearer ' + token,
            },
            success: res => {
                console.log('获取客户渠道', res);
                if (res.code === 200) {
                    this.setState({
                        customerSource: res.data
                    });
                }
            }
        });
    }

    // 选择客户渠道
    changeCustomerSource(value) {
        this.setState({
            currentCustomerSource: value
        });
    }

    // 显示订单的商品信息
    showProduct(orderId) {
        this.setState({
            productVisibile: true
        });
        $.ajax({
            url: `${config.CrmOrder}/getProductList`,
            type: 'get',
            headers: {
                'Authorization': 'Bearer ' + token,
            },
            data: {
                orderId
            },
            success: res => {
                console.log('获取订单的商品信息', res);
                if (res.code === 200) {
                    this.setState({
                        updateOrderProduct: { orderId, product: res.data }
                    });
                }
            }
        });
    }

    // 修改商品
    changeProductStatus() {
        this.setState({
            productStatus: true
        });
    }

    // 修改商品的数量
    changeProductNumber(product, e) {
        const { updateOrderProduct } = this.state;
        updateOrderProduct.product.forEach(item => {
            if (item.productId === product.productId) {
                e.target.value = parseInt(e.target.value) || '';
                item.buyNumber = e.target.value || 1;
            }
        });
    }

    // 隐藏商品模态框
    hiddenProduct() {
        this.setState({
            productVisibile: false,
            productStatus: false,
            updateOrderProduct: {}
        });
    }

    // 显示商品删除模态框
    showProductDel(product) {
        this.setState({
            productDelVisible: true,
            deleteProduct: product
        });
    }

    // 确认删除商品
    handleDelProduct() {
        const { deleteProduct, updateOrderProduct } = this.state;
        updateOrderProduct.product.forEach((item, index) => {
            if (item.productId === deleteProduct.productId) {
                updateOrderProduct.product.splice(index, 1);
            }
        });
        this.setState({
            productDelVisible: false,
            deleteProduct: {},
            updateOrderProduct
        });
    }

    // 取消删除商品
    cancelDelProduct() {
        this.setState({
            productDelVisible: false,
            deleteProduct: {},
        });
    }

    // 显示添加商品模态框
    showAddProduct() {
        this.setState({
            addProductVisible: true
        });
        this.getCategoryList();
        this.getProductList();
    }

    // 获取分类列表
    getCategoryList() {
        $.ajax({
            url: `${config.JuseGoods}/categories_sk/GetCategoryList`,
            type: 'post',
            headers: {
                'Authorization': 'Bearer ' + token,
            },
            success: res => {
                console.log('获取分类列表', res);
                if (res.code === 200) {
                    const loop = (list) => {
                        list.map(item => {
                            item.value = item.categoryid;
                            item.label = item.categoryname;
                            if (item.children.length) {
                                loop(item.children);
                            } else {
                                delete item.children;
                            }
                        })
                    };
                    loop(res.data);
                    this.setState({
                        categoryList: res.data
                    });
                }
            }
        });
    }

    // 获取商品列表
    getProductList() {
        const { productName: productname, productPage: pageindex, productPageSize: pagesize, currentCategoryId: categoryid } = this.state;
        $.ajax({
            url: `${config.JuseGoods}/products/GetZXproductList`,
            type: 'post',
            headers: {
                'Authorization': 'Bearer ' + token,
            },
            data: {
                productname,
                pageindex,
                pagesize,
                categoryid
            },
            success: res => {
                console.log('获取商品列表', res);
                if (res.code === 200) {
                    res.data.forEach((item, index) => {
                        item.key = index;
                    });
                    this.setState({
                        productList: res.data,
                        productTotal: res.datacount
                    });
                }
            }
        });
    }

    // 隐藏添加商品模态框
    hiddenAddProduct() {
        this.setState({
            addProductVisible: false
        });
    }

    // 商品列表显示
    productColumns() {
        return [{
            title: '内码',
            dataIndex: 'productnumber',
            width: '7%',
        }, {
            title: '产品名称',
            dataIndex: 'productname',
            width: '6%',
        }, {
            title: '库存',
            dataIndex: 'zx_stock',
            width: '6%',
        }, {
            title: '待发货数量',
            dataIndex: 'crmpendeliverynumber',
            width: '6%',
        }, {
            title: '单位',
            dataIndex: 'packing',
            width: '4%',
        }, {
            title: '状态',
            dataIndex: '',
            width: '6%',
            render: record => {
                let text;
                switch (record.salestatus) {
                    case 0:
                        text = '未发步';
                        break;
                    case 1:
                        text = '上架区';
                        break;
                    case 2:
                        text = '下架区';
                        break;
                }
                return text;
            }
        }, {
            title: '选择',
            dataIndex: '',
            width: '5%',
            render: record => {
                if (record.salestatus === 1 && record.zx_stock) {
                    return <div><a href='javascript:void(0)' onClick={this.selectProduct.bind(this, record)}>确认选择</a></div>;
                }
                return <div style={{ color: '#ccc' }}>确认选择</div>;
            }
        }];
    }

    // 输入商品名称
    inputProduct(e) {
        this.setState({
            productName: e.target.value
        });
    }

    // 搜索商品
    searchProduct() {
        this.setState({
            productPage: 1
        }, () => {
            this.getProductList();
        });
    }

    // 改变商品分页
    changeProductPage(page) {
        this.setState({
            productPage: page
        }, () => {
            this.getProductList();
        });
    }

    // 选择商品
    selectProduct(product) {
        const { updateOrderProduct } = this.state;
        let result = true;
        updateOrderProduct.product.forEach(item => {
            if (item.productId == product.productid) {
                result = false;
            }
        });
        if (result) {
            updateOrderProduct.product.push({
                productId: product.productid,
                number: 1,
                'product.productname': product.productname
            });
            this.setState({
                updateOrderProduct
            });
        }
    }

    // 选择分类
    selectCategory(list) {
        this.setState({
            currentCategoryId: list[list.length - 1]
        });
    }

    // 修改订单的商品
    updateProduct() {
        const { updateOrderProduct } = this.state;
        const productList = updateOrderProduct.product.map(item => {
            return {
                id: item.productId,
                buyNumber: item.number
            }
        });
        if (!productList.length) {
            return message.error('请选择商品!');
        }
        $.ajax({
            url: `${config.CrmOrder}/updateProduct`,
            type: 'post',
            headers: {
                'Authorization': 'Bearer ' + token,
            },
            data: {
                orderId: updateOrderProduct.orderId,
                productList
            },
            success: res => {
                console.log('修改订单的商品', res);
                if (res.code === 200) {
                    this.setState({
                        productVisibile: false,
                        productStatus: false,
                        updateOrderProduct: {}
                    });
                } else if (res.code === 202) {
                    message.error('该订单状态不能修改商品!');
                } else if (res.code === 204) {
                    message.error(`${res.productName}已下架!`);
                } else if (res.code === 205) {
                    message.error(`${res.productName}库存不足!`);
                }
            }
        });
    }

    // 获取部门以及员工
    getDepartment() {
        $.ajax({
            url: `${config.JuseManager}/department/tree`,
            type: 'get',
            headers: {
                'Authorization': 'Bearer ' + token,
            },
            success: res => {
                console.log('获取部门以及员工', res);
                if (res.code === 200) {
                    const loop = (list) => {
                        list.map(item => {
                            item.value = item.id;
                            item.label = item.name;
                            if (item.son.length) {
                                item.children = item.son;
                                loop(item.children);
                            }
                        })
                    };
                    loop(res.dep);
                    this.setState({
                        departmentList: res.dep
                    });
                }
            }
        });
    }

    // 选择部门
    selectDepartment(list) {
        const id = list[list.length - 1];
        let staffList = [];
        if (id) {
            const loop = (list, id) => {
                let arr = [];
                list.forEach(item => {
                    if (item.id == id) {
                        arr = arr.concat(item.userlist);
                        item.son.forEach(value => {
                            arr = arr.concat(loop(item.son, value.id));
                        });
                    } else {
                        arr = arr.concat(loop(item.son, id));
                    }
                });
                return arr;
            }
            const { departmentList } = this.state;
            staffList = loop(departmentList, id);
        }
        staffList.forEach((item, index) => {
            item.key = index;
        });
        console.log(staffList);
        this.setState({
            staffList,
            currentStaff: undefined,
            currentDepartment: id,
            currentDepartmentList: list
        });
    }

    // 选择员工
    selectStaff(value) {
        this.setState({
            currentStaff: value
        });
    }

    // 选择模态框中的部门
    selectModalDepartment(list) {
        this.setState({
            modalDepartmentList: list,
            modalDepartment: list[list.length - 1]
        });
    }

    // 搜索员工
    searchStaff() {
        this.setState({
            staffPage: 1
        }, () => {
            this.getStaffList();
        });
    }

    // 分配订单
    allotOrder(record) {
        const { selectOrder } = this.state;
        const orderList = selectOrder.map(item => {
            return item.orderId;
        });
        $.ajax({
            url: `${config.CrmOrder}/allotOrder`,
            type: 'post',
            headers: {
                'Authorization': 'Bearer ' + token,
            },
            data: {
                id: record.id,
                orderList
            },
            success: res => {
                console.log('分配订单', res);
                if (res.code === 200) {
                    message.success('分配订单成功!', 3);
                    this.getOrderList();
                }
            }
        });
    }

    // 显示共用模态框
    showPublicModal(value) {
        const { selectOrder } = this.state;
        if (!selectOrder.length) {
            return message.error('请先选择订单');
        }
        this.setState({
            publicVisible: true,
            publicStatus: value
        });
    }

    // 隐藏共用模态框
    hiddenPublicModal() {
        this.setState({
            publicVisible: false,
            publicStatus: ''
        });
    }

    // 共用模态框的提示
    showPublicTitle() {
        const { publicStatus, selectOrder } = this.state;
        let text;
        switch (publicStatus) {
            case 1:
                text = `是否确定对该${selectOrder.length}条订单审核通过？`;
                break;
            case 2:
                text = `是否恢复该${selectOrder.length}条订单的审核状态？`;
                break;
            case 3:
                text = `是否确定该${selectOrder.length}条订单的定金已到账？`;
                break;
            case 4:
                text = `是否恢复该${selectOrder.length}条订单的定金审核状态？`;
                break;
            case 5:
                text = `是否签收该${selectOrder.length}条订单？`;
                break;
            case 6:
                text = `是否把该${selectOrder.length}条订单恢复到仓库之前的状态？`;
                break;
        }
        return text;
    }

    // 处理共用模态框事件
    handlePublicModal() {
        const { publicStatus, selectOrder, userInfo } = this.state;
        const orderList = selectOrder.map(item => {
            return item.orderId;
        });
        this.setState({
            publicVisible: false
        });
        switch (publicStatus) {
            case 1:
                this.examineOrder(orderList, userInfo.id);
                break;
            case 2:
                this.cancelExamineOrder(orderList);
                break;
            case 3:
                this.examineDeposit(orderList, userInfo.id);
                break;
            case 4:
                this.cancelExamineDeposit(orderList);
                break;
            case 5:
                this.sign(orderList, userInfo.id);
                break;
            case 6:
                this.cancelWarehouse(orderList);
                break;
        }
    }

    // 审核订单
    examineOrder(orderList, id) {
        $.ajax({
            url: `${config.CrmOrder}/examineOrder`,
            type: 'post',
            headers: {
                'Authorization': 'Bearer ' + token,
            },
            data: {
                id,
                orderList
            },
            success: res => {
                console.log('审核订单', res);
                if (res.code === 200) {
                    message.success('审核订单成功!', 3);
                    this.getOrderList();
                }
            }
        });
    }

    // 取消订单审核(恢复订单状态)
    cancelExamineOrder(orderList) {
        $.ajax({
            url: `${config.CrmOrder}/cancelExamineOrder`,
            type: 'post',
            headers: {
                'Authorization': 'Bearer ' + token,
            },
            data: {
                orderList
            },
            success: res => {
                console.log('取消订单审核', res);
                if (res.code === 200) {
                    message.success('恢复订单状态成功!', 3);
                    this.getOrderList();
                }
            }
        });
    }

    // 定金审核
    examineDeposit(orderList, id) {
        $.ajax({
            url: `${config.CrmOrder}/examineDeposit`,
            type: 'post',
            headers: {
                'Authorization': 'Bearer ' + token,
            },
            data: {
                id,
                orderList
            },
            success: res => {
                console.log('定金审核', res);
                if (res.code === 200) {
                    message.success('定金审核成功!', 3);
                    this.getOrderList();
                }
            }
        });
    }

    // 取消定金审核(恢复定金状态)
    cancelExamineDeposit(orderList) {
        $.ajax({
            url: `${config.CrmOrder}/cancelExamineDeposit`,
            type: 'post',
            headers: {
                'Authorization': 'Bearer ' + token,
            },
            data: {
                orderList
            },
            success: res => {
                console.log('恢复定金状态', res);
                if (res.code === 200) {
                    message.success('恢复定金状态成功!', 3);
                    this.getOrderList();
                }
            }
        });
    }

    // 签收
    sign(orderList, id) {
        $.ajax({
            url: `${config.CrmOrder}/sign`,
            type: 'post',
            headers: {
                'Authorization': 'Bearer ' + token,
            },
            data: {
                id,
                orderList
            },
            success: res => {
                console.log('签收', res);
                if (res.code === 200) {
                    message.success('签收成功!', 3);
                    this.getOrderList();
                }
            }
        });
    }

    // 恢复仓库订单(取消仓库操作)
    cancelWarehouse(orderList) {
        $.ajax({
            url: `${config.CrmOrder}/cancelWarehouse`,
            type: 'post',
            headers: {
                'Authorization': 'Bearer ' + token,
            },
            data: {
                orderList
            },
            success: res => {
                console.log('恢复仓库订单', res);
                if (res.code === 200) {
                    message.success('恢复仓库订单成功!', 3);
                    this.getOrderList();
                }
            }
        });
    }

    // 获取支付类型
    getPayType() {
        $.ajax({
            url: `${config.CrmSettings}/crm_paytype/GetPayType`,
            type: 'post',
            headers: {
                'Authorization': 'Bearer ' + token,
            },
            success: res => {
                console.log('获取支付类型', res);
                if (res.code === 200) {
                    const loop = (list) => {
                        list.map(item => {
                            item.value = item.id;
                            item.label = item.paytypename;
                            if (item.children.length) {
                                loop(item.children);
                            } else {
                                delete item.children;
                            }
                        })
                    };
                    loop(res.data);
                    this.setState({
                        payType: res.data
                    });
                }
            }
        });
    }

    // 选择支付方式
    selectPayType(list) {
        this.setState({
            currentPayType: list
        });
    }

    render() {
        const { orderList, orderPage, orderPageSize, orderTotal, orderSizeOptions, orderStatus, dateType, startDate, endDate, depositStatus, assigningVisible, staffPage, staffPageSize, staffTotal, staffSizeOptions, staffList, updateOrderProduct, keyword } = this.state;
        const { productList, productPage, productPageSize, productTotal } = this.state;
        const { getFieldDecorator } = this.props.form;
        const formItemLayout = {
            labelCol: {
                xs: { span: 24 },
                sm: { span: 6 },
            },
            wrapperCol: {
                xs: { span: 24 },
                sm: { span: 14 },
            },
        };
        return (
            <Form>
                <div className='goods-label'>
                    <div className='goods-label-cont clearfix'>
                        <div className='goods-label-cont-nav clearfix'>
                            <Breadcrumb separator='>'>
                                <Breadcrumb.Item>会员管理</Breadcrumb.Item>
                                <Breadcrumb.Item>直销订单列表</Breadcrumb.Item>
                            </Breadcrumb>
                        </div>
                        <div className='member-content-Search clearfix'>
                            <div className='addetd addetd-z  addetd-cg'>
                                <FormItem>
                                    {
                                        getFieldDecorator('productName')(
                                            <Input className='addetd-a-r' addonBefore='商品名称' placeholder='请输入' />
                                        )
                                    }
                                </FormItem>
                            </div>
                            <div className='addetd addetd-z  addetd-cg'>
                                <FormItem>
                                    {
                                        getFieldDecorator('consigneeName')(
                                            <Input className='addetd-a-r' addonBefore='收货人' placeholder='请输入' />
                                        )
                                    }
                                </FormItem>
                            </div>
                            <div className='addetd addetd-z addetd-cg'>
                                <FormItem>
                                    {
                                        getFieldDecorator('shipOrderNumber')(
                                            <Input className='addetd-a-r' addonBefore='快递单号' placeholder='请输入' />
                                        )
                                    }
                                </FormItem>
                            </div>
                            <div className='addetd addetd-z addetd-cg'>
                                <FormItem>
                                    {
                                        getFieldDecorator('consigneePhone')(
                                            <Input className='addetd-a-r' addonBefore='电话号码' placeholder='请输入' />
                                        )
                                    }
                                </FormItem>
                            </div>
                            <div className='addetd addetd-z addetd-cg'>
                                <FormItem>
                                    {
                                        getFieldDecorator('parcelNumber')(
                                            <Input className='addetd-a-r' addonBefore='包裹号' placeholder='请输入' />
                                        )
                                    }
                                </FormItem>
                            </div>
                        </div>
                        <div className='member-content-Search clearfix'>
                            <div className='addetd addetd-a indtner ouegt-c'>
                                <InputGroup compact>
                                    <Input addonBefore='订单状态' />
                                    <Select value={orderStatus} onChange={this.selectOrderStatus.bind(this)} allowClear>
                                        <Option value='0'>未处理</Option>
                                        <Option value='1'>已处理</Option>
                                        <Option value='2'>待发货</Option>
                                        <Option value='3'>已发货</Option>
                                        <Option value='4'>已签收</Option>
                                    </Select>
                                </InputGroup>
                            </div>
                            <div className='addetd addetd-a indtner  shuerwq-1   shuzhazha-1'>
                                <InputGroup compact>
                                    <Input addonBefore='时间类型' />
                                    <Select value={dateType} onChange={this.selectDateType.bind(this)} allowClear>
                                        <Option value='1'>预计发货时间</Option>
                                        <Option value='2'>下单时间</Option>
                                        <Option value='3'>审核时间</Option>
                                        <Option value='4'>发货时间</Option>
                                        <Option value='5'>签收时间</Option>
                                    </Select>
                                </InputGroup>
                            </div>
                            <div className='addetd addetd-a addetd-kk youyoyt-to  adrtt-a' style={{ marginLeft: 20 }}>
                                <InputGroup compact>
                                    <div className='chengge-d iugnt-a'>
                                        <DatePicker
                                            onChange={this.selectStartDate.bind(this)}
                                            value={startDate}
                                        />
                                    </div>
                                </InputGroup>
                            </div>
                            <div className='addetd addetd-a addetd-kk adrtt-a adrtt-b'>
                                <InputGroup compact>
                                    <div className='chengge-d iugnt-a'>
                                        <DatePicker
                                            onChange={this.selectEndDate.bind(this)}
                                            value={endDate}
                                        />
                                    </div>
                                </InputGroup>
                            </div>
                            <div className='addetd addetd-a indtner ouegt-c'>
                                <InputGroup compact>
                                    <Input addonBefore='定金状态' />
                                    <Select value={depositStatus} onChange={this.selectDepositStatus.bind(this)} allowClear>
                                        <Option value='0'>未付款</Option>
                                        <Option value='1'>已付款</Option>
                                        <Option value='2'>待定</Option>
                                    </Select>
                                </InputGroup>
                            </div>
                            <div className='addetd addetd-a indtner ouegt-c'>
                                <InputGroup compact>
                                    <Input addonBefore='客户来源' />
                                    <Select value={this.state.currentCustomerSource} onChange={this.changeCustomerSource.bind(this)} allowClear>
                                        {this.state.customerSource.map((item, index) => {
                                            return <Option value={String(item.id)} key={index}>{item.sourcename}</Option>
                                        })}
                                    </Select>
                                </InputGroup>
                            </div>
                        </div>
                        <div className='member-content-Search clearfix'>
                            <div className='addetd addetd-a cake-aoot' style={{ marginRight: 0 }}>
                                <InputGroup compact>
                                    <span className='chengge-a fkov-tyo fkov-tyo-a'>归属人</span>
                                    <Cascader options={this.state.departmentList} placeholder='请选择部门!' changeOnSelect onChange={this.selectDepartment.bind(this)} value={this.state.currentDepartmentList} />
                                </InputGroup>
                            </div>
                            <div className='addetd addetd-a indtner  indtner-trs indtner-trtyu'>
                                <InputGroup compact>
                                    <Select value={this.state.currentStaff} onChange={this.selectStaff.bind(this)} className='setOrder-user-personnel' placeholder='请选择员工!' allowclear>
                                        {
                                            this.state.staffList.map((item, index) => {
                                                return <Option value={String(item.id)} key={index}>{item.name}</Option>
                                            })
                                        }
                                    </Select>
                                </InputGroup>
                            </div>
                            <div className='addetd addetd-a cake-aoot'>
                                <InputGroup compact>
                                    <span className='chengge-a fkov-tyo fkov-tyo-a  zhifuy-eo'>支付类型</span>
                                    <Cascader value={this.state.currentPayType} options={this.state.payType} placeholder='请选择支付类型' changeOnSelect onChange={this.selectPayType.bind(this)} />
                                </InputGroup>
                            </div>
                            <Button type='primary' style={{ marginLeft: 50 }} className='member-button' icon='search' onClick={this.searchOrderList.bind(this)}>搜索</Button>
                            <Button type='primary' className='member-button' icon='reload' onClick={this.resetOrderList.bind(this)}>重置</Button>
                        </div>

                        <div className='chengge-e  your_sa' style={{ marginBottom: 20 }}>
                            {/* <Button className='member-button-aa' type='primary' style={{ marginLeft: 20 }} onClick={() => this.generateBarCode()}>生成快递号</Button>
                                <Button className='member-button-aa' type='primary' onClick={() => this.printExpressBill()}>打印快递单</Button> */}

                            {keyword.includes('setOrder') && <Button className='member-button-aa' type='primary' style={{ marginLeft: 20, width: 100 }} onClick={this.setOrder.bind(this)}>新建订单</Button>}
                            {keyword.includes('allotOrder') && <Button className='member-button-aa' onClick={this.showAssigningModal.bind(this)} style={{ width: 100 }} type='primary'>分配订单</Button>}
                            <Modal
                                title='员工列表'
                                visible={assigningVisible}
                                onCancel={this.hiddenAssigningModal.bind(this)}
                                width={'1000px'}
                                maskClosable={false}
                                footer={null}
                            >
                                <div className='delets_gg'>
                                    <div className='addetd addetd-z' style={{ marginRight: 0 }}>
                                        <FormItem>
                                            {
                                                getFieldDecorator('staffText')(
                                                    <Input className='addetd-a-r' addonBefore='姓名/手机号/登录名' placeholder='请输入' />
                                                )
                                            }
                                        </FormItem>
                                    </div>
                                    <div className='addetd addetd-a cake-aoot' style={{ marginRight: 0 }}>
                                        <InputGroup compact>
                                            <Cascader value={this.state.modalDepartmentList} options={this.state.departmentList} placeholder='请选择部门!' changeOnSelect onChange={this.selectModalDepartment.bind(this)} />
                                        </InputGroup>
                                    </div>
                                    <div className='addetd addetd-a yryre-1' >
                                        <InputGroup compact>
                                            <Input addonBefore='状态' />
                                            <Select value={this.state.staffStatus} onChange={this.selectStaffStatus.bind(this)} allowClear>
                                                <Option value='1'>在职</Option>
                                                <Option value='2'>试用</Option>
                                            </Select>
                                        </InputGroup>
                                    </div>
                                    <Button type='primary' style={{ marginLeft: 50 }} className='member-button' style={{ width: 100, height: 40 }} icon='search' onClick={this.searchStaff.bind(this)}>搜索</Button>
                                </div>
                                <Table
                                    columns={this.showStaffColumns()}
                                    dataSource={this.state.modalStaffList}
                                    pagination={false}
                                    bordered
                                />
                                <div className='goods-label-let clearfix' style={{ float: 'none' }}>
                                    <div className='floor-ppagi'>
                                        {
                                            staffTotal == 0
                                                ?
                                                <p className='floor-ppagip'>共{staffTotal}条记录</p>
                                                :
                                                <p className='floor-ppagip'>当前显示{1 + (staffPage - 1) * staffPageSize}—{staffPage * staffPageSize > staffTotal ? staffTotal : staffPage * staffPageSize}条记录，共{staffTotal}条记录</p>
                                        }
                                        <Pagination
                                            current={staffPage}
                                            total={staffTotal || 1}
                                            defaultPageSize={staffPageSize}
                                            onChange={this.changeStaffPage.bind(this)}
                                            showSizeChanger
                                            pageSizeOptions={staffSizeOptions}
                                            onShowSizeChange={this.changeStaffSize.bind(this)}
                                        />
                                    </div>
                                </div>
                            </Modal>
                            <Modal
                                title={false}
                                footer={false}
                                visible={this.state.publicVisible}
                                onCancel={this.hiddenPublicModal.bind(this)}
                                maskClosable={false}
                            >
                                <div className='delets_gg'>
                                    <p className='delets_gg1'>温馨提示</p>
                                    <p>{this.showPublicTitle()}</p>
                                    <p style={{ marginTop: 30 }}>
                                        <Button className='member-button-aa' onClick={this.handlePublicModal.bind(this)} style={{ width: 100 }} type='primary'>确定</Button>
                                        <Button className='member-button-aa' onClick={this.hiddenPublicModal.bind(this)} style={{ width: 100, marginLeft: 30 }} type='primary'>取消</Button>
                                    </p>
                                </div>
                            </Modal>
                            {keyword.includes('examineOrder') && <Button className='member-button-aa' style={{ width: 100 }} type='primary' onClick={this.showPublicModal.bind(this, 1)}>订单审核</Button>}
                            {keyword.includes('cancelExamineOrder') && <Button className='member-button-aa' style={{ width: 120 }} type='primary' onClick={this.showPublicModal.bind(this, 2)}>恢复订单状态</Button>}
                            {keyword.includes('examineDeposit') && <Button className='member-button-aa' style={{ width: 100 }} type='primary' onClick={this.showPublicModal.bind(this, 3)}>订金审核</Button>}
                            {keyword.includes('cancelExamineDeposit') && <Button className='member-button-aa' style={{ width: 120 }} type='primary' onClick={this.showPublicModal.bind(this, 4)}>恢复订金状态</Button>}
                            {keyword.includes('sign') && <Button className='member-button-aa' style={{ width: 80 }} type='primary' onClick={this.showPublicModal.bind(this, 5)}>签收</Button>}
                            {keyword.includes('cancelWarehouse') && <Button className='member-button-aa' style={{ width: 120 }} type='primary' onClick={this.showPublicModal.bind(this, 6)}>恢复仓库订单</Button>}
                            {/* <Button className='member-button-aa' style={{ width: 80 }} type='primary' onClick={this.showPublicModal.bind(this, 7)}>导出</Button> */}
                        </div>
                        <div className='allgoods-table clearfix'>
                            <Table
                                columns={this.showOrderColumns()}
                                dataSource={orderList}
                                pagination={false}
                                bordered
                                rowSelection={this.showRowSelection()}
                            />
                        </div>
                        <div className='goods-label-let'>
                            <div className='floor-ppagi'>
                                {
                                    orderTotal == 0
                                        ?
                                        <p className='floor-ppagip'>共{orderTotal}条记录</p>
                                        :
                                        <p className='floor-ppagip'>当前显示{1 + (orderPage - 1) * orderPageSize}—{orderPage * orderPageSize > orderTotal ? orderTotal : orderPage * orderPageSize}条记录，共{orderTotal}条记录</p>
                                }
                                <Pagination
                                    current={orderPage}
                                    total={orderTotal || 1}
                                    defaultPageSize={orderPageSize}
                                    onChange={this.changeOrderPage.bind(this)}
                                    showSizeChanger
                                    pageSizeOptions={orderSizeOptions}
                                    onShowSizeChange={this.changeOrderSize.bind(this)}
                                />
                            </div>
                            <div style={{ textAlign: 'right' }}>
                                <span style={{ color: '#FF0000', marginRight: '50px' }}>总金额：{this.state.orderMoneySum}</span>
                                <span style={{ color: '#336600', marginRight: '50px' }}>代收金额：{this.state.collectionMoneySum}</span>
                                <span style={{ color: '#0000FF', marginRight: '20px' }}>定金：{this.state.depositSum}</span>
                            </div>
                        </div>
                    </div>
                </div>
                <Modal
                    visible={this.state.productVisibile}
                    maskClosable={false}
                    footer={null}
                    width={590}
                    onCancel={this.hiddenProduct.bind(this)}
                >
                    <p className='shuishy'>商品信息</p>
                    <div className='shuishy-a'>订单编号：{updateOrderProduct.orderId}</div>
                    <Row className='shuishy-b'>
                        <Col span={14}>产品名称</Col>
                        <Col span={5}>数量</Col>
                        <Col span={5}>操作</Col>
                    </Row>
                    {updateOrderProduct.product && updateOrderProduct.product.map((item, index) => {
                        if (this.state.productStatus) {
                            return <Row className='crmorderlist-product-row clearfix shuishy-c' key={index}>
                                <Col span={14} className='shuishy-d'>{item['product.productname']}</Col>
                                <Col span={5} className='shuishy-d' style={{ borderLeft: '1px solid #e5e5e5', borderRight: '1px solid #e5e5e5' }}><Input style={{ height: '80%' }} defaultValue={item.number} onChange={this.changeProductNumber.bind(this, item)} /></Col>
                                <Col span={5} className='shuishy-d'><a href='javascript:void(0)' onClick={this.showProductDel.bind(this, item)}>删除</a></Col>
                            </Row>
                        }
                        return <Row className='crmorderlist-product-row clearfix shuishy-c' key={index}>
                            <Col span={14} className='shuishy-d'>{item['product.productname']}</Col>
                            <Col span={5} className='shuishy-d' >{item.number}</Col>
                            <Col span={5} className='shuishy-d'></Col>
                        </Row>
                    })}
                    {
                        this.state.productStatus
                            ?
                            <div><Button style={{ marginTop: 20, }} onClick={this.showAddProduct.bind(this)}>添加商品</Button></div>
                            :
                            ''
                    }
                    {
                        this.state.productStatus
                            ?
                            <p style={{ textAlign: 'center' }}><Button type='primary' style={{ marginTop: 20 }} onClick={this.updateProduct.bind(this)}>保存</Button></p>
                            :
                            <p style={{ textAlign: 'center' }}><Button type='primary' style={{ marginTop: 20, }} onClick={this.changeProductStatus.bind(this)}>修改</Button></p>
                    }
                </Modal>
                <Modal
                    title='删除'
                    visible={this.state.productDelVisible}
                    onOk={this.handleDelProduct.bind(this)}
                    onCancel={this.cancelDelProduct.bind(this)}
                    maskClosable={false}
                >
                    <div className='delets_gg'>
                        <p className='delets_gg1'>温馨提示</p>
                        <p>删除后不可恢复，是否继续删除？</p>
                    </div>
                </Modal>
                <Modal title='商品列表'
                    visible={this.state.addProductVisible}
                    onOk={this.hiddenAddProduct.bind(this)}
                    onCancel={this.hiddenAddProduct.bind(this)}
                    maskClosable={false}
                    width={'1000px'}
                >
                    <div className='delets_gg'>
                        <div className='addetd addetd-z'>
                            <Input className='addetd-a-r' addonBefore='商品名称' placeholder='请输入' onChange={this.inputProduct.bind(this)} />
                        </div>
                        <div className='addetd addetd-a yryreddd-1'>
                            <Cascader options={this.state.categoryList} onChange={this.selectCategory.bind(this)} placeholder='--产品分类--' changeOnSelect />
                        </div>
                        <Button type='primary' style={{ marginLeft: 50 }} className='member-button' style={{ width: 100, height: 40 }} icon='search' onClick={this.searchProduct.bind(this)}>搜索</Button>
                    </div>
                    <Table
                        columns={this.productColumns()}
                        dataSource={productList}
                        pagination={false}
                        bordered
                    />
                    <div className='goods-label-let clearfix' style={{ float: 'none' }}>
                        <div className='floor-ppagi'>
                            <p className='floor-ppagip'>当前显示 {productTotal ? 1 + (productPage - 1) * productPageSize : 0} - {productPage * productPageSize > productTotal ? productTotal : productPage * productPageSize} 条记录 共 {productTotal} 条记录</p>
                            <Pagination current={productPage} total={productTotal} defaultPageSize={productPageSize} onChange={this.changeProductPage.bind(this)} />
                        </div>
                    </div>
                </Modal>
            </Form>
        )
    }
}

export default Form.create()(CrmOrderlist);
